package com.terra.ns.imp.common.mybatis.config

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
import com.terra.ns.imp.common.mybatis.base.MpConstants
import com.terra.ns.imp.common.satoken.utils.LoginUtils
import com.terra.ns.imp.common.util.exception.hasExceptionReturnNull
import com.terra.ns.imp.common.vo.entity.BaseTableField
import com.terra.ns.imp.common.vo.entity.BaseTableOperatorField
import org.apache.ibatis.reflection.MetaObject
import java.time.LocalDateTime

/**
@author qins
@date 2023/6/1
@desc insert-update自动填充
 */
class AutoFillMetaObjectHandler : MetaObjectHandler {

    /**
     * 插入时自动填充
     */
    override fun insertFill(metaObject: MetaObject) {
        this.strictInsertFill(metaObject, BaseTableField::createDate.name, { LocalDateTime.now() }, LocalDateTime::class.java)
        this.strictInsertFill(metaObject, BaseTableField::modifyDate.name, { LocalDateTime.now() }, LocalDateTime::class.java)
        if(metaObject.originalObject is BaseTableOperatorField) {
            val userCode = hasExceptionReturnNull { LoginUtils.getUserCode() } ?: MpConstants.SYSTEM_OPERATOR
            this.strictInsertFill(metaObject, BaseTableOperatorField::createUser.name, { userCode }, String::class.java)
            this.strictInsertFill(metaObject, BaseTableOperatorField::modifyUser.name, { userCode }, String::class.java)
        }
    }

    override fun updateFill(metaObject: MetaObject) {
        this.strictInsertFill(metaObject, BaseTableField::modifyDate.name, { LocalDateTime.now() }, LocalDateTime::class.java)
        if(metaObject.originalObject is BaseTableOperatorField) {
            val userCode = hasExceptionReturnNull { LoginUtils.getUserCode() } ?: MpConstants.SYSTEM_OPERATOR
            this.strictInsertFill(metaObject, BaseTableOperatorField::modifyUser.name, { userCode }, String::class.java)
        }
    }
}